package core;

import gui.swing.DownloadList;
import gui.MainSystray;

import java.util.ArrayList;
import java.util.List;

import core.config.Configuration;
import core.connector.Connector;

public class DownloadManager
{
    private static DownloadManager downloadManager=null;
    public synchronized static DownloadManager getInstance()
    {
        if (downloadManager==null)
            downloadManager=new DownloadManager();
        return downloadManager;
    }
    private DownloadManager(){}

    private static final List<Connector> connectors = new ArrayList<Connector>();
    public synchronized final int getNumberOfWorkingConnectors()
    {
        int working=0;
        for (Connector connector : connectors)
        {
            if (connector.doing.isWorking())
                working++;
        }
        return working;
    }
    public synchronized final int getNumberOfWaitingConnectors()
    {
        int waiting=0;
        for (Connector connector : connectors)
        {
            if (connector.doing.isWaiting())
                waiting++;
        }
        return waiting;
    }
    public synchronized void startNext()
    {
        //ATIVANDO PAUSADOS
        int numberOfAccountsToSimultaneouslyDownload =Configuration.getInstance().getNumberOfAccountsToSimultaneouslyDownload();
        int numberOfWorkingConnectors = getNumberOfWorkingConnectors();
        if (numberOfAccountsToSimultaneouslyDownload > numberOfWorkingConnectors )
        {
            for (Connector connector : connectors)
            {
                if (connector.doing.isWaiting())
                {
                    connector.startDownload();
                    DownloadList.getInstance().updateDownloadGUI(connector);
                    break;
                }
            }
        }
        DownloadList.getInstance().updateConnectorsList(connectors);
    }
    public synchronized void cancelDownload(Connector connector)
    {
        //STOP DOWNLOADING
        connector.stopDownload();
        //REMOVE FROM THE LIST OF DONWLOADS
        connectors.remove(connector);
        //REFRESH THE LIST
        MainSystray.guiFactory.getDownloadList().updateConnectorsList(connectors);
    }
    /**
     * Add Connector to the download list display (remove from the finished list)
     * @param connector
     */
    public synchronized final void addDonwload(Connector connector)
    {
        if (!connectors.contains(connector))
            connectors.add(connector);
        MainSystray.guiFactory.getDownloadList().updateConnectorsList(connectors);
    }
}
